package cn.maihe.elg.operation.web.system;

import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.model.dto.InnerBaseResp;
import cn.maihe.elg.operation.model.enums.AuditStatusEnum;
import cn.maihe.elg.operation.model.enums.BusinessStatusEnum;
import cn.maihe.elg.operation.model.enums.UserStatusEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.Query;
import cn.maihe.elg.operation.model.vo.system.OcrReqDTO;
import cn.maihe.elg.operation.model.vo.system.OcrRespDTO;
import cn.maihe.elg.operation.model.vo.system.OrgKtCustomerVO;
import cn.maihe.elg.operation.model.vo.system.OrganizationVO;
import cn.maihe.elg.operation.repository.entity.KtCustomerDO;
import cn.maihe.elg.operation.repository.entity.KtCustomerVo;
import cn.maihe.elg.operation.repository.entity.OrganizationDO;
import cn.maihe.elg.operation.repository.entity.UserDO;
import cn.maihe.elg.operation.service.business.ExchangeCenterService;
import cn.maihe.elg.operation.service.business.KtCustomerService;
import cn.maihe.elg.operation.service.system.OrganizationService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AddAuthReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AddCompanyXbCertReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AddCompanyXbCertRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AddPersonXbCertReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AddPersonXbCertRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.AuthInfoVO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.CertSealRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.ChangeAuthReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.CurrentXbStateRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.DoDelayCertReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.GetAuthTokenRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.QueryAuthReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.QueryAuthRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.enums.KtCertState;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.AddAuthService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.AddCompanyXbCertService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.AddPersonXbCertService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.CertSealService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.ChangeAuthService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.CurrentXbStateService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.DoDelayCertService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.GetAuthSMSService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.GetAuthTokenService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service.QueryAuthService;
import cn.maihe.elg.operation.supports.ocr.AliyunOcrService;
import cn.maihe.elg.operation.utils.Base64Util;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.StringUtil;
import cn.maihe.elg.operation.utils.UserContextUtil;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.jsonwebtoken.lang.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JHWei on 2018-07-13.
 * @ 创建日期：2018-07-13
 */
@Api(value = "机构管理接口", tags = {"机构管理"})
@RestController
@Slf4j
public class OrganizationController {

    @Resource
    private OrganizationService organizationService;
    @Resource
    private ExchangeCenterService exchangeCenterService;
    @Resource
    private ImageUploadConfig imageUploadConfig;
    @Resource
    private AliyunOcrService aliyunOcrService;
    @Resource
    private KtCustomerService ktCustomerService;
    @Resource
    private AddCompanyXbCertService addCompanyXbCertService;
    @Resource
    private AddPersonXbCertService addPersonXbCertService;
    @Resource
    private CertSealService certSealService;
    @Resource
    private CurrentXbStateService currentXbStateService;
    @Resource
    private ChangeAuthService changeAuthService;
    @Resource
    private QueryAuthService queryAuthService;
    @Resource
    private AddAuthService addAuthService;
    @Resource
    private DoDelayCertService doDelayCertService;
    @Resource
    private GetAuthSMSService getAuthSMSService;
    @Resource
    private GetAuthTokenService getAuthTokenService;

    @ApiOperation(value = "新增机构")
    @RequestMapping(value = "/api/organization", method = RequestMethod.POST)
    public void createOrganization(@RequestBody OrganizationVO createOrganizationVO) {
        OrganizationDO organization = new OrganizationDO();
        UserDO user = new UserDO();
        BeanUtils.copyProperties(createOrganizationVO, organization);
        organization.setBusinessStatus(BusinessStatusEnum.CLOSED.getValue());
        organization.setAuditStatus(AuditStatusEnum.AUDIT_NO.getValue());
        user.setUsername(createOrganizationVO.getUsername());
        user.setName(createOrganizationVO.getFullName());
        user.setMobileNo(createOrganizationVO.getContactTel());
        user.setEmail(createOrganizationVO.getContactEmail());
        user.setPassword(createOrganizationVO.getPassword());
        user.setOrgCode(createOrganizationVO.getOrgCode());
        user.setType(UserType.ORG.getType());
        user.setStatus(UserStatusEnum.NORMAL.toString());
        organizationService.createOrganization(organization,user);
    }

    @ApiOperation(value = "查询首页统计信息", notes = "首页统计信息")
    @RequestMapping(value = "/api/organization/total", method = RequestMethod.POST)
    public Map getTotal() {
        Map map = new HashMap();
        map.put("centCount",exchangeCenterService.selectCountBySql("selectCenterCountHome"));
        map.put("auditCount",organizationService.getAuditTotal());
        return map;
    }

    @ApiOperation(value = "查询机构列表", notes = "根据机构名称(模糊查找)、机构代码查询机构列表")
    @RequestMapping(value = "/api/organization/list", method = RequestMethod.POST)
    public PageInfo<OrganizationDO> findAll(@RequestBody Query query) {
        return organizationService.findOrganizationByPage(query);
    }

    @ApiOperation(value = "获取机构详情")
    @RequestMapping(value = "/api/organization/{id}", method = RequestMethod.GET)
    public OrganizationDO getOrganization(@PathVariable Long id) {
        return organizationService.getOrganization(id);
    }

    @ApiOperation(value = "获取租户代码")
    @RequestMapping(value = "/api/organizationCode/{id}", method = RequestMethod.GET)
    public OrganizationDO getTenant(@PathVariable Long id) {
        OrganizationDO organization = new OrganizationDO();
        organization.setOrgCode(organizationService.getOrganizationCode(id));
        return organization;
    }

    @ApiOperation(value = "修改机构信息")
    @RequestMapping(value = "/api/organization", method = RequestMethod.PUT)
    public void updateOrganization(@RequestBody OrganizationVO updateOrganizationVO) {
        OrganizationDO organization = new OrganizationDO();
        BeanUtils.copyProperties(updateOrganizationVO, organization);
        if("1".equals(updateOrganizationVO.getSubmitType())){
            organization.setAuditStatus(AuditStatusEnum.AUDITING.getValue());
        }else{
            organization.setAuditStatus(AuditStatusEnum.AUDIT_NO.getValue());
        }
        organizationService.modifyOrganization(organization);
    }

    @ApiOperation(value = "删除机构")
    @RequestMapping(value = "/api/organization/{id}", method = RequestMethod.DELETE)
    public void deleteOrganization(@PathVariable Long id) {
        organizationService.deleteOrganization(id);
    }


    @ApiOperation(value = "ocr接口", notes = "ocr信息")
    @RequestMapping(value = "/api/organization/ocr", method = RequestMethod.POST)
    public OcrRespDTO ocr(@Validated @RequestBody OcrReqDTO ocrReqDTO) {
        String imageBase64 = Base64Util.img_base64(imageUploadConfig.getPath()+ocrReqDTO.getImage());

        OcrRespDTO respDTO = new OcrRespDTO();
        ApiResponse apiResponse =  aliyunOcrService.ocr(ocrReqDTO.getType(),imageBase64);
        log.info("ocr return:{}", JSONObject.toJSONString(apiResponse));
        respDTO.setCode(apiResponse.getCode()+"");
        respDTO.setMsg(apiResponse.getMessage());
        if(apiResponse.getCode() != 200){
            List<String> messages = apiResponse.getHeaders().get("X-Ca-Error-Message");
            if(messages!=null&&messages.size()>0){
                respDTO.setMsg(messages.get(0));
            }
        }
        respDTO.setContent(new String(apiResponse.getBody()));
        return respDTO;
    }


    @ApiOperation(value = "获取机构关联凯特云签信息")
    @RequestMapping(value = "/api/organization/ktCustomer/{id}", method = RequestMethod.GET)
    public OrgKtCustomerVO getOrganizationKtCustomer(@PathVariable Long id) {
        KtCustomerDO ktCustomerDO = ktCustomerService.selectByOrgId(id, "1");
        if (ktCustomerDO == null) {
            ktCustomerDO = KtCustomerDO.builder().orgId(id).build();
        }
        KtCustomerDO legalKtCustomerDO = ktCustomerService.selectByOrgId(id, "2");
        if (legalKtCustomerDO == null) {
            legalKtCustomerDO = KtCustomerDO.builder().orgId(id).build();
        }
        OrgKtCustomerVO orgKtCustomerVO = OrgKtCustomerVO.build(ktCustomerDO.buildVo(), legalKtCustomerDO.buildVo());

        return orgKtCustomerVO;
    }

    @ApiOperation(value = "提交机构云签制证信息")
    @RequestMapping(value = "/api/organization/ktCustomer/add", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public InnerBaseResp applyKtCustomer(@RequestBody OrgKtCustomerVO vo) {
        //机构入驻凯特云签
        OrganizationDO organizationDO = organizationService.getOrganization(vo.getOrgId());
        InnerBaseResp innerBaseResp = this.applyKtCustomer4Company(vo, organizationDO);
        String msg1 = innerBaseResp.getMessage();
        if (innerBaseResp.getRespCode().isSuccess()) {
            innerBaseResp = this.applyKtCustomer4Legal(vo, organizationDO);
            if (innerBaseResp.getRespCode().isSuccess()) {
                return InnerBaseResp.success(innerBaseResp.getData(), msg1 + "_" + innerBaseResp.getMessage());
            }
        }

        return innerBaseResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public InnerBaseResp applyKtCustomer4Legal(KtCustomerVo vo, OrganizationDO organizationDO) {
        KtCustomerDO ktCustomerDO = ktCustomerService.selectByOrgId(vo.getOrgId(), "2");
        if (ktCustomerDO == null) {
            ktCustomerDO = KtCustomerDO.builder()
                    .id(IdGenerate.getId())
                    .orgId(organizationDO.getId())
                    .certType("2")
                    .bidderId(null)
                    .applyPic(vo.getApplyPic())
                    .autherIdcard(vo.getAutherIdcard())
                    .autherMobile(vo.getAutherMobile())
                    .autherName(vo.getAutherName())
                    .handlerIdcard(vo.getHandlerIdcard())
                    .handlerIdPic(vo.getHandlerIdPic())
                    .handlerMobile(vo.getHandlerMobile())
                    .handlerName(vo.getHandlerName())
                    .managerIdcard(vo.getManagerIdcard())
                    .managerMobile(vo.getManagerMobile())
                    .managerName(vo.getManagerName())
                    .userModified(UserContextUtil.getCurUserName())
                    .build();
            ktCustomerService.insert(ktCustomerDO);
        } else {
            //证书状态 0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功
            KtCertState certState = KtCertState.resolve(ktCustomerDO.getCertState());
            if (certState != null && certState != KtCertState.NOT_EXISTS) {
                if (certState == KtCertState.CERT_MAKING || certState == KtCertState.SEAL_MAKING) {
                    ktCustomerDO = this.queryResult4ZT(ktCustomerDO);
                    certState = KtCertState.resolve(ktCustomerDO.getCertState());
                }
                return InnerBaseResp.success("法人证书已申请，当前进度:" + certState.getDesc());
            }
            vo.setId(ktCustomerDO.getId());
            ktCustomerDO = KtCustomerDO.of(vo);
            ktCustomerService.updateById(ktCustomerDO);
        }

        AuthInfoVO manager = AuthInfoVO.builder()
                .name(ktCustomerDO.getManagerName())
                .idCard(ktCustomerDO.getManagerIdcard())
                .mobile(ktCustomerDO.getManagerMobile())
                .build();
        AuthInfoVO auth = AuthInfoVO.builder()
                .name(ktCustomerDO.getAutherName())
                .idCard(ktCustomerDO.getAutherIdcard())
                .mobile(ktCustomerDO.getAutherMobile())
                .build();
        AddPersonXbCertReqDTO addPersonXbCertReqDTO = AddPersonXbCertReqDTO.builder()
                .certCn(organizationDO.getLegalName())
                .certNumber(organizationDO.getLegalIdcard())
                .certMobile(organizationDO.getLegalMobile())
                .superAuthList(Lists.newArrayList(manager))
                .jbrName(ktCustomerDO.getHandlerName())
                .jbrIdCard(ktCustomerDO.getHandlerIdcard())
                .jbrMobile(ktCustomerDO.getHandlerMobile())
                .file6(Base64Util.img_base64(imageUploadConfig.getPath() + ktCustomerDO.getApplyPic()))
                .file5(Base64Util.img_base64(imageUploadConfig.getPath() + organizationDO.getLegalIdcardPic()))
                .file4(Base64Util.img_base64(imageUploadConfig.getPath() + ktCustomerDO.getHandlerIdPic()))
                .build();
        //管理员默认也是授权人，仅但授权人手机号码与管理员不一致时上送授权人
        if (!auth.getMobile().equals(manager.getMobile())) {
            addPersonXbCertReqDTO.setAuthList(Lists.newArrayList(auth));
        }

        String tradeId = organizationDO.getLegalIdcard();
        InnerBaseResp innerBaseResp = addPersonXbCertService.doRequest(tradeId, addPersonXbCertReqDTO);
        if (innerBaseResp.getRespCode().isSuccess()) {
            AddPersonXbCertRespDTO respDTO = (AddPersonXbCertRespDTO) innerBaseResp.getData();
            String origCode = innerBaseResp.getOrigCode();
            String orderId = respDTO.getOrderId();
            if (StringUtil.containsAny(origCode, "0000", "0008")) {
                //当code为0000时说明操作成功 当code为0008时说明订单记录已经存在
                ktCustomerDO.setOrderId(orderId);
                //state：新办状态（0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功）
                ktCustomerDO.setCertState(KtCertState.CERT_MAKING.getCertState());
                ktCustomerService.updateById(ktCustomerDO);

                //制证
                CertSealRespDTO certSealRespDTO = certSealService.makeCertSeal(ktCustomerDO.getOrderId());

                ktCustomerDO.setCertState(KtCertState.SEAL_OK.getCertState());
                ktCustomerDO.setUserId(certSealRespDTO.getUserId());
                ktCustomerDO.setCertName(certSealRespDTO.getCertName());
                ktCustomerDO.setCertNumber(certSealRespDTO.getCertNumber());
                ktCustomerDO.setCertBeginTime(DateUtil.formateDate(certSealRespDTO.getBeginTime(), DateUtil.FORMAT_DADETIME));
                ktCustomerDO.setCertEndTime(DateUtil.formateDate(certSealRespDTO.getEndTime(), DateUtil.FORMAT_DADETIME));
                ktCustomerService.updateById(ktCustomerDO);
                innerBaseResp = InnerBaseResp.success(ktCustomerDO, "法人证书证章制作成功");
            } else if (origCode.equals("0099")) {
                ktCustomerDO.setOrderId(orderId);
                ktCustomerDO.setCertState(KtCertState.SEAL_MAKING.getCertState());
                ktCustomerService.updateById(ktCustomerDO);
                innerBaseResp = InnerBaseResp.success(ktCustomerDO, "法人证书已制证未制章");
                //通过前端或者后管轮询机制查询结果
            } else {
                //其他未明确定义含义的作为审核失败处理
            }
        }

        return innerBaseResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public InnerBaseResp applyKtCustomer4Company(KtCustomerVo vo, OrganizationDO organizationDO) {
        KtCustomerDO ktCustomerDO = ktCustomerService.selectByOrgId(vo.getOrgId(), "1");
        if (ktCustomerDO == null) {
            ktCustomerDO = KtCustomerDO.builder()
                    .id(IdGenerate.getId())
                    .orgId(organizationDO.getId())
                    .certType("1")
                    .bidderId(null)
                    .applyPic(vo.getApplyPic())
                    .autherIdcard(vo.getAutherIdcard())
                    .autherMobile(vo.getAutherMobile())
                    .autherName(vo.getAutherName())
                    .handlerIdcard(vo.getHandlerIdcard())
                    .handlerIdPic(vo.getHandlerIdPic())
                    .handlerMobile(vo.getHandlerMobile())
                    .handlerName(vo.getHandlerName())
                    .managerIdcard(vo.getManagerIdcard())
                    .managerMobile(vo.getManagerMobile())
                    .managerName(vo.getManagerName())
                    .userModified(UserContextUtil.getCurUserName())
                    .build();
            ktCustomerService.insert(ktCustomerDO);
        } else {
            //证书状态 0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功
            KtCertState certState = KtCertState.resolve(ktCustomerDO.getCertState());
            if (certState != null && certState != KtCertState.NOT_EXISTS) {
                if (certState == KtCertState.CERT_MAKING || certState == KtCertState.SEAL_MAKING) {
                    ktCustomerDO = this.queryResult4ZT(ktCustomerDO);
                    certState = KtCertState.resolve(ktCustomerDO.getCertState());
                }
                return InnerBaseResp.success("企业证书已申请，当前进度:" + certState.getDesc());
            }
            vo.setId(ktCustomerDO.getId());
            ktCustomerDO = KtCustomerDO.of(vo);
            ktCustomerService.updateById(ktCustomerDO);
        }

        AuthInfoVO manager = AuthInfoVO.builder()
                .name(ktCustomerDO.getManagerName())
                .idCard(ktCustomerDO.getManagerIdcard())
                .mobile(ktCustomerDO.getManagerMobile())
                .build();
        AuthInfoVO auth = AuthInfoVO.builder()
                .name(ktCustomerDO.getAutherName())
                .idCard(ktCustomerDO.getAutherIdcard())
                .mobile(ktCustomerDO.getAutherMobile())
                .build();
        AddCompanyXbCertReqDTO addCompanyXbCertReqDTO = AddCompanyXbCertReqDTO.builder()
                .certCn(organizationDO.getFullName())
                .certNumber(organizationDO.getCreditCode())
                .superAuthList(Lists.newArrayList(manager))
                .jbrName(ktCustomerDO.getHandlerName())
                .jbrIdCard(ktCustomerDO.getHandlerIdcard())
                .jbrMobile(ktCustomerDO.getHandlerMobile())
                .file1(Base64Util.img_base64(imageUploadConfig.getPath() + ktCustomerDO.getApplyPic()))
                .file3(Base64Util.img_base64(imageUploadConfig.getPath() + organizationDO.getBusinessLicensePic()))
                .file4(Base64Util.img_base64(imageUploadConfig.getPath() + ktCustomerDO.getHandlerIdPic()))
                .build();
        //管理员默认也是授权人，仅但授权人手机号码与管理员不一致时上送授权人
        if (!auth.getMobile().equals(manager.getMobile())) {
            addCompanyXbCertReqDTO.setAuthList(Lists.newArrayList(auth));
        }

        String tradeId = organizationDO.getCreditCode();
        InnerBaseResp innerBaseResp = addCompanyXbCertService.doRequest(tradeId, addCompanyXbCertReqDTO);
        if (innerBaseResp.getRespCode().isSuccess()) {
            AddCompanyXbCertRespDTO respDTO = (AddCompanyXbCertRespDTO) innerBaseResp.getData();
            String origCode = innerBaseResp.getOrigCode();
            String orderId = respDTO.getOrderId();
            if (StringUtil.containsAny(origCode, "0000", "0008")) {
                //当code为0000时说明操作成功 当code为0008时说明订单记录已经存在
                ktCustomerDO.setOrderId(orderId);
                //state：新办状态（0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功）
                ktCustomerDO.setCertState(1);
                ktCustomerService.updateById(ktCustomerDO);

                //制证
                CertSealRespDTO certSealRespDTO = certSealService.makeCertSeal(ktCustomerDO.getOrderId());

                ktCustomerDO.setCertState(3);
                ktCustomerDO.setUserId(certSealRespDTO.getUserId());
                ktCustomerDO.setCertName(certSealRespDTO.getCertName());
                ktCustomerDO.setCertNumber(certSealRespDTO.getCertNumber());
                ktCustomerDO.setCertBeginTime(DateUtil.formateDate(certSealRespDTO.getBeginTime(), DateUtil.FORMAT_DADETIME));
                ktCustomerDO.setCertEndTime(DateUtil.formateDate(certSealRespDTO.getEndTime(), DateUtil.FORMAT_DADETIME));
                ktCustomerService.updateById(ktCustomerDO);
                innerBaseResp = InnerBaseResp.success(ktCustomerDO, "企业证书证章制作成功");
            } else if (origCode.equals("0009")) {
                ktCustomerDO.setOrderId(orderId);
                ktCustomerDO.setCertState(2);
                ktCustomerService.updateById(ktCustomerDO);
                innerBaseResp = InnerBaseResp.success(ktCustomerDO, "企业证书已制证未制章");
                //通过前端或者后管轮询机制查询结果
            } else {
                //其他未明确定义含义的作为审核失败处理
            }
        }

        return innerBaseResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public KtCustomerDO queryResult4ZT(KtCustomerDO ktCustomerDO) {

        if (StringUtil.isNotEmpty(ktCustomerDO.getOrderId())) {
            CurrentXbStateRespDTO respDTO = currentXbStateService.queryCurrentXbState(ktCustomerDO.getOrderId());
            //state;//新办状态（0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功）
            int status = respDTO.getState();
            ktCustomerDO.setCertState(status);
            if (status == 3) {
                ktCustomerDO.setCertState(3);
                ktCustomerDO.setUserId(respDTO.getUserId());
                ktCustomerDO.setCertName(respDTO.getCertCn());
                ktCustomerDO.setCertNumber(respDTO.getCertNumber());
                ktCustomerDO.setCertBeginTime(respDTO.getBeginTime());
                ktCustomerDO.setCertEndTime(respDTO.getEndTime());
            } else if (status == 0) {
                throw new RuntimeException("查询云签证书信息orderId未找到[" + status + ":" + respDTO.getMsg() + "]");
            } else if (status == 1) {
                CertSealRespDTO certSealRespDTO = certSealService.makeCertSeal(ktCustomerDO.getOrderId());
                ktCustomerDO.setCertState(3);
                ktCustomerDO.setUserId(certSealRespDTO.getUserId());
                ktCustomerDO.setCertName(certSealRespDTO.getCertName());
                ktCustomerDO.setCertNumber(certSealRespDTO.getCertNumber());
                ktCustomerDO.setCertBeginTime(DateUtil.formateDate(certSealRespDTO.getBeginTime(), DateUtil.FORMAT_DADETIME));
                ktCustomerDO.setCertEndTime(DateUtil.formateDate(certSealRespDTO.getEndTime(), DateUtil.FORMAT_DADETIME));
            }
            ktCustomerService.updateById(ktCustomerDO);
        }

        return ktCustomerDO;
    }

    @ApiOperation(value = "机构云签证书信息操作")
    @RequestMapping(value = "/api/organization/ktCustomer/operate/{type}", method = RequestMethod.POST)
    public InnerBaseResp ztKtCustomer(@PathVariable("type") Integer type, @RequestBody OrgKtCustomerVO vo) {
        //type=1 证书查询 2=证书延期 3=变更授权人 4=token重置
        //机构入驻凯特云签
        OrganizationDO organizationDO = organizationService.getOrganization(vo.getOrgId());
        if (organizationDO == null) {
            return InnerBaseResp.error(null, "查无此机构信息");
        }
        KtCustomerDO ktCustomerDO = ktCustomerService.selectByOrgId(vo.getOrgId(), "1");
        if (ktCustomerDO == null) {
            return InnerBaseResp.error(null, "查无此机构云签信息,请重新进行企业制章");
        }
        KtCustomerDO legalKtCustomerDO = ktCustomerService.selectByOrgId(vo.getOrgId(), "2");
        if (legalKtCustomerDO == null) {
            return InnerBaseResp.error(null, "查无此机构法人云签信息,请重新进行法人制章");
        }

        if (type == 1) {
            ktCustomerDO = this.queryResult4ZT(ktCustomerDO);
            legalKtCustomerDO = this.queryResult4ZT(legalKtCustomerDO);
            OrgKtCustomerVO reVo = OrgKtCustomerVO.build(ktCustomerDO.buildVo(), legalKtCustomerDO.buildVo());
            return InnerBaseResp.success(reVo, "证书查询完成");
        }

        //证书状态 0是找不到数据，1是待制证，2是已制证未制章，3是证章制作成功
        KtCertState certState = KtCertState.resolve(ktCustomerDO.getCertState());
        if (certState == null || certState == KtCertState.NOT_EXISTS) {
            return InnerBaseResp.error(ktCustomerDO, "当前机构云签信息非法，请重新进行企业制章");
        }
        if (type == 3) {
            //3=变更授权人
            try {
                Assert.hasText(vo.getAutherName(), "变更授权人名称不能为空");
                Assert.hasText(vo.getAutherMobile(), "变更授权人手机号码不能为空");
                Assert.hasText(vo.getAutherIdcard(), "变更授权人身份证号不能为空");
                //机构变更
                InnerBaseResp<KtCustomerDO> orgResp = this.doChangeAuth(ktCustomerDO, vo);
                OrgKtCustomerVO reVo = OrgKtCustomerVO.build(orgResp.getData().buildVo(), vo.getLegalVo());
                if (!orgResp.getRespCode().isSuccess()) {
                    return InnerBaseResp.of(orgResp.getRespCode(),"企业变更授权人失败:"+orgResp.getMessage(),reVo);
                }
                //法人变更
                InnerBaseResp<KtCustomerDO>  legalResp = this.doChangeAuth(legalKtCustomerDO, vo);
                reVo.setLegalVo(legalResp.getData().buildVo());
                if (!legalResp.getRespCode().isSuccess()) {
                    return InnerBaseResp.of(legalResp.getRespCode(),"法人变更授权人失败:"+legalResp.getMessage(),reVo);
                }
                return InnerBaseResp.success(reVo,"变更授权人成功");
            } catch (Exception e) {
                log.error("变更授权人失败:{}", e.getMessage(), e);
                return InnerBaseResp.error(ktCustomerDO, "变更授权人失败:" + e.getMessage());
            }
        }

        //证书延期及token重置必须已制证成功
        if (certState == KtCertState.SEAL_OK) {
            if (type == 2) {
                //证书延期
                InnerBaseResp<KtCustomerDO> orgResp = this.doDelayCertService(ktCustomerDO);
                OrgKtCustomerVO reVo = OrgKtCustomerVO.build(orgResp.getData().buildVo(), vo.getLegalVo());
                if (!orgResp.getRespCode().isSuccess()) {
                    return InnerBaseResp.of(orgResp.getRespCode(),"企业证书延期失败:"+orgResp.getMessage(),reVo);
                }
                InnerBaseResp<KtCustomerDO> legalResp = this.doDelayCertService(legalKtCustomerDO);
                reVo.setLegalVo(legalResp.getData().buildVo());
                if (!legalResp.getRespCode().isSuccess()) {
                    return InnerBaseResp.of(legalResp.getRespCode(),"法人证书延期失败:"+legalResp.getMessage(),reVo);
                }
                return InnerBaseResp.success(reVo, "证书延期成功");
            } else if (type == 4) {
                //token重置
                try {
                    Assert.hasText(vo.getAutherName(), "获取token短信验证码不能为空");
                    List<GetAuthTokenRespDTO.TokenInfo> tokenInfos = getAuthTokenService.getAutoToken(vo.getOpId(), vo.getSmsCode());
                    for (int i = 0; i < tokenInfos.size(); i++) {
                        GetAuthTokenRespDTO.TokenInfo tokenInfo = tokenInfos.get(i);
                        if ("1".equals(tokenInfo.getType())) {
                            ktCustomerDO.setToken(tokenInfo.getToken());
                            ktCustomerDO.setTokenExpiryTime(tokenInfo.getEndTime());
                            ktCustomerService.updateById(ktCustomerDO);
                        }else if ("2".equals(tokenInfo.getType())) {
                            legalKtCustomerDO.setToken(tokenInfo.getToken());
                            legalKtCustomerDO.setTokenExpiryTime(tokenInfo.getEndTime());
                            ktCustomerService.updateById(legalKtCustomerDO);
                        }
                    }
                    OrgKtCustomerVO reVo = OrgKtCustomerVO.build(ktCustomerDO.buildVo(), legalKtCustomerDO.buildVo());
                    return InnerBaseResp.success(reVo, "获取token成功");
                } catch (Exception e) {
                    log.error("获取token失败:{}", e.getMessage(), e);
                    return InnerBaseResp.error(vo, "获取token失败:" + e.getMessage());
                }
            } else if (type == 5) {
                //获取token短信验证码
                try {
                    List<String> dbUserIds = Lists.newArrayList(ktCustomerDO.getUserId(), legalKtCustomerDO.getUserId());
                    String opId = getAuthSMSService.sendSmsAndGetOpId(ktCustomerDO.getAutherMobile(), dbUserIds);
                    vo.setOpId(opId);
                    return InnerBaseResp.success(vo, "token短信验证码已发送,注意查收并回填");
                } catch (Exception e) {
                    log.error("token短信验证码发送异常:{}", e.getMessage(), e);
                    return InnerBaseResp.error(ktCustomerDO, "token短信验证码发送异常:" + e.getMessage());
                }
            }
        }

        return InnerBaseResp.error(null, "未知操作类型或流程错误");
    }

    private InnerBaseResp<KtCustomerDO> doDelayCertService(KtCustomerDO ktCustomerDO) {
        DoDelayCertReqDTO reqDTO = new DoDelayCertReqDTO();
        reqDTO.setUserId(ktCustomerDO.getUserId());
        reqDTO.setJbrIdCard(ktCustomerDO.getHandlerIdcard());
        reqDTO.setJbrMobile(ktCustomerDO.getHandlerMobile());
        reqDTO.setJbrName(ktCustomerDO.getHandlerName());
        String tradeId = ktCustomerDO.getUserId();
        try {
            doDelayCertService.doService(tradeId, reqDTO);
            ktCustomerDO = this.queryResult4ZT(ktCustomerDO);
            return InnerBaseResp.success(ktCustomerDO, "证书延期成功");
        } catch (Exception e) {
            log.error("证书延期失败:{}", e.getMessage(), e);
            return InnerBaseResp.error(ktCustomerDO, "证书延期失败:" + e.getMessage());
        }
    }

    private InnerBaseResp<KtCustomerDO> doChangeAuth(KtCustomerDO ktCustomerDO, OrgKtCustomerVO vo) {
        String tradeId = ktCustomerDO.getUserId();
        if (ktCustomerDO.getAutherMobile().equals(vo.getAutherMobile())
                && ktCustomerDO.getAutherIdcard().equals(vo.getAutherIdcard())
                && ktCustomerDO.getAutherName().equals(vo.getAutherName())
        ) {
            //与原授权人信息一致
            return InnerBaseResp.success(ktCustomerDO, "与原授权人信息一致无需变更");
        }
        if (ktCustomerDO.getManagerMobile().equals(vo.getAutherMobile())
                && ktCustomerDO.getManagerIdcard().equals(vo.getAutherIdcard())
                && ktCustomerDO.getManagerName().equals(vo.getAutherName())
        ) {
            //与管理员一致
            return InnerBaseResp.success(ktCustomerDO, "与管理员信息一致无需变更");
        } else {
            //db中原管理员与授权人手机号码一致且查询凯特若不存在授权人情况则添加，已存在则更新
            if (ktCustomerDO.getManagerMobile().equals(vo.getAutherMobile())) {
                return InnerBaseResp.error(ktCustomerDO, "变更授权人手机号码不能和管理员手机号码一致");
            } else if (ktCustomerDO.getManagerIdcard().equals(vo.getAutherIdcard())) {
                return InnerBaseResp.error(ktCustomerDO, "变更授权人身份证号不能和管理员身份证号一致");
            }

            QueryAuthReqDTO reqDto = new QueryAuthReqDTO();
            reqDto.setUserId(ktCustomerDO.getUserId());
            reqDto.setType("1");
            //默认取第一条数据，不存在则为空 管理员默认也是授权人，但查询授权人却无管理员的授权人信息且又不能添加管理员号码的授权人
            QueryAuthRespDTO respDTO = queryAuthService.doService(tradeId, reqDto);

            if (respDTO != null) {
                //根据userId+oldMobile变更授权信息
                ChangeAuthReqDTO reqDTO = new ChangeAuthReqDTO();
                reqDTO.setUserId(ktCustomerDO.getUserId());
                reqDTO.setOldMobile(respDTO.getMobile());
                reqDTO.setName(vo.getAutherName());
                reqDTO.setMobile(vo.getAutherMobile());
                reqDTO.setIdCard(vo.getAutherIdcard());
                changeAuthService.doService(tradeId, reqDTO);
            } else {

                //添加授权人
                AddAuthReqDTO reqDTO = new AddAuthReqDTO();
                reqDTO.setUserId(ktCustomerDO.getUserId());
                reqDTO.setName(vo.getAutherName());
                reqDTO.setMobile(vo.getAutherMobile());
                reqDTO.setIdCard(vo.getAutherIdcard());
                addAuthService.doService(tradeId, reqDTO);
            }

            ktCustomerDO.setAutherIdcard(vo.getAutherIdcard());
            ktCustomerDO.setAutherMobile(vo.getAutherMobile());
            ktCustomerDO.setAutherName(vo.getAutherName());
            ktCustomerService.updateById(ktCustomerDO);

            return InnerBaseResp.success(ktCustomerDO, "变更授权人完成");
        }
    }
}
